<!--
 @description 帮助中心内容详情
 @fileName Detail.vue
 @author zengqiongying
 @created 2022/02/22 14:12:30
-->

<template>
  <div class="help-center-list-page">
    <Header fixed arrow :show-search="false" />
    <div v-if="!hideHead" class="help-list-header">
      <div class="search-cell">
        <SearchInput ref="searchInput" v-model="searchValue" :class="['bg-search-input']" @focus="focusHandle" />
      </div>
      <div class="icon-menu" @click="showPop=true" />
    </div>
    <PopTree
      v-model="categoryId"
      :visible.sync="showPop"
      @clickItem="handleToList"
    />

    <div class="help-center-list-main">
      <div class="detail-main-page">
        <div class="detail-title">
          <h1>{{ detailData.title }}</h1>
          <div class="d-time">
            <span>更新时间: {{ detailData.lastUpdateTime | filterTime }}</span>
            <span class="icon-view">{{ detailData.readNum || 0 }}</span>
          </div>
        </div>

        <div ref="htmlcontent" class="detail-content" @click="handleViewImage($event)" v-html="detailData.content" />

        <div class="video-main">
          <div v-for="(item,i) in videoList" :key="i" class="video-content">
            <!-- <video
              v-if="item.fileUrl"
              :src="item.fileUrl"
              controls="controls"
              webkit-playsinline="true"
              x5-video-player-type="h5"
              x5-video-orientation="portraint"
              style="max-width:100%"
              :poster="videoCoverImg"
            >
              您的浏览器不支持 video 标签。
            </video> -->

            <Player
              v-if="item.fileUrl"
              ref="player"
              :srcset="item.fileUrl"
              :landscape="false"
              @requestFullscreen="requestFullscreenHandle"
              @exitFullscreen="exitFullscreenHandle"
              @click.stop.native
            />
          </div>
        </div>
        <div class="btn-copy">
          <van-button
            type="primary"
            class="btn btn-copy-content"
            :data-clipboard-text="clipboardCopyContent"
            @click="copyText"
          >复制内容</van-button>
        </div>

        <div v-if="detailData.attachments && detailData.attachments.length>0" class="attach-box">
          <h1>相关附件</h1>
          <div class="attach-list">
            <div v-for="(item,index) in detailData.attachments" :key="index" class="list">
              <span
                :class="['att-icon',{
                  'xlsx':item.type==='xlsx' || item.type==='xls',
                  'word':item.type==='doc'||item.type==='docx',
                  'ppt':item.type==='ppt' || item.type==='pptx',
                  'pdf':item.type==='pdf',
                  'zip':item.type==='zip',
                  'img':item.type==='png' ||item.type==='jpg' || item.type==='jpeg' || item.type==='bpm' ,
                }]"
              />
              <div class="att-name">{{ item.fileName || item.fileUrl }}</div>
              <div class="btn-down" @click="downLoad(item)">下载</div>
            </div>
          </div>
        </div>

        <div v-if="detailData && detailData.id" class="article-opt">
          <span class="txt">您觉得这篇资料怎么样呢？</span>
          <div class="btn-zan" :class="{'activve':detailData.likeType===-1}" @click="handleLike(-1)">
            <svg-icon class="icon-cai" icon-class="dianzanjiayoubangone-line" />
            <div><!--{{ detailData.unLikeNum || 0 }}--> 踩一下</div>
          </div>
          <div class="btn-zan" :class="{'activve':detailData.likeType===1}" @click="handleLike(1)">
            <svg-icon icon-class="dianzanjiayoubangone-line" />
            <div><!--{{ detailData.likeNum || 0 }}--> 赞一下</div>
          </div>
        </div>

        <template v-if="!hideHead">
          <div v-if="perPage && perPage.id" class="article-page active" @click="refreshDetail(perPage.id)">
            上一篇: {{ perPage.title }}
          </div>
          <div v-if="nextPage && nextPage.id" class="article-page active" @click="refreshDetail(nextPage.id)">
            下一篇: {{ nextPage.title }}
          </div>
        </template>

      </div>

    </div>

  </div>
</template>

<script>

import Header from './components/Header'
import SearchInput from '@/components/SearchInput'
import PopTree from './components/PopTree'
import { getContentDetail, getUpDownContents, updateLikeType, getWatermarkFile } from '@/apis/helpCenter'
import { parseTime } from '@/utils'
import { judgeSys } from '@/utils/native'
import { saveAs } from 'file-saver'
import { ImagePreview } from 'vant'
import Player from '@/components/Player'
import Cookies from 'js-cookie'
import Clipboard from 'clipboard'

export default {
  name: 'HelpCenterDetail',
  components: {
    Header, SearchInput, PopTree, Player
  },
  filters: {
    filterTime(val) {
      return parseTime(val, '{y}.{m}.{d} {h}:{i}:{s}')
    }
  },
  data() {
    return {
      imgHost: `${process.env.VUE_APP_ADS_STATIC}`,
      searchValue: '',
      hideHead: [1, '1'].includes(this.$route.query.hide),
      contentId: this.$route.params.id || '',
      categoryId: '',
      showPop: false,
      detailData: '',
      pageData: [],
      videoList: [],
      waterMarkDownUrl: `${process.env.VUE_APP_BASE_API}/app/v1/helpCenterContent/downloadAttachmentAndAddWatermark/`,
      abelWaterTypes: ['pdf', 'jpg', 'jpeg', 'png', 'bmp'], // ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'] // 可添加水印的类型
      clipboardCopyContent: ''
    }
  },
  computed: {
    videoCoverImg() {
      if (this.detailData.covers && this.detailData.covers.length > 0) {
        const url = this.detailData.covers[0].fileUrl
        const fileUrl = this.concatHost(url)
        return fileUrl
      }
      return ''
    },
    perPage() {
      if (this.pageData.length > 1) {
        return this.pageData[0]
      }
      return {}
    },
    nextPage() {
      if (this.pageData.length === 2) {
        return this.pageData[1]
      }
      return {}
    }
  },
  watch: {

  },
  created() {
    this.getDetailData()
  },
  beforeDestroy() {
    this.showPop = false
  },
  methods: {
    concatHost(src) {
      return /^http.+/.test(src) ? src : `${this.imgHost}/${src}`
    },
    requestFullscreenHandle() {
      this.$emit('requestFullscreen')
    },
    exitFullscreenHandle() {
      this.$emit('exitFullscreen')
    },
    refreshDetail(id) {
      this.$router.replace({
        name: 'HelpCenterDetail',
        params: { id },
        query: {
          c: this.$route.query.c || '',
          name: this.$route.query.name || ''
        }
      })
      /* this.contentId = id
      window.scrollTo(0, 0)
      this.getDetailData() */
    },
    getDetailData() {
      getContentDetail(this.contentId).then(res => {
        this.detailData = res.data || ''
        this.categoryId = this.detailData.categoryId

        const list = this.detailData.videos || []
        this.videoList = list.map(v => {
          const fileUrl = this.concatHost(v.fileUrl)
          return { ...v, ...{ fileUrl }}
        })
      })
      const params = {
        contentId: this.contentId,
        sort: this.$route.query.s || '',
        categoryId: this.$route.query.c || '',
        title: this.$route.query.name || ''
      }
      getUpDownContents(params).then(res => {
        this.pageData = res.data || []
      })
    },
    focusHandle() {
      this.$router.push({ name: 'HelpCenterSearch' })
    },
    handleToList(categoryId) {
      this.showPop = false
      this.$router.push({ name: 'HelpCenterList', query: { cate: categoryId }})
    },
    /**
     * @param {Number} likeType 类型：1 点赞 ， -1 点踩
    */
    handleLike(likeType) {
      const oldLikeType = this.detailData.likeType
      if (oldLikeType === likeType) return
      const { id, likeNum = 0, unLikeNum = 0 } = this.detailData
      if (likeType === 1) {
        this.$set(this.detailData, 'likeNum', likeNum + 1)
        if (this.detailData.likeType === -1) {
          this.$set(this.detailData, 'unLikeNum', unLikeNum > 0 ? unLikeNum - 1 : 0)
        }
      } else {
        this.$set(this.detailData, 'unLikeNum', unLikeNum + 1)
        if (this.detailData.likeType === 1) {
          this.$set(this.detailData, 'likeNum', likeNum > 0 ? likeNum - 1 : 0)
        }
      }
      this.$set(this.detailData, 'likeType', likeType)

      updateLikeType({ contentId: id, likeType }).then(res => {
        // this.getNoticeDetailData()
      })
    },
    image2Base64(img) {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.width, img.height)
      const dataURL = canvas.toDataURL('image/png')
      return dataURL
    },
    getBase64(fileUrl) {
      return new Promise((resolve, reject) => {
        window.URL = window.URL || window.webkitURL
        // TODO:仅同源获取
        var xhr = new XMLHttpRequest()
        xhr.open('get', fileUrl, true)
        // 至关重要
        xhr.responseType = 'blob'
        xhr.onload = function() {
          console.log(xhr)
          if (xhr.status === 200) {
            // 得到一个blob对象
            var blob = xhr.response
            console.log('blob', blob)
            // 至关重要
            const oFileReader = new FileReader()
            oFileReader.onloadend = function(e) {
              // 此处拿到的已经是 base64的图片了
              const base64 = e.target.result
              console.log('方式一》》》》》》》》》', base64)
              resolve(base64)
            }
            oFileReader.readAsDataURL(blob)
          } else {
            reject('文件读取失败')
          }
        }
        xhr.send()
      })
    },
    async downLoad(file) {
      let url = this.$formatURL(file.fileUrl, `${process.env.VUE_APP_ADS_STATIC}/`)
      const name = file.fileName || new Date().getTime()
      if (file.isWatermark === 1 && this.abelWaterTypes.includes(file.type)) {
        url = `${this.waterMarkDownUrl}${file.id}`
      }
      const params = { downloadURL: url, fileName: name }
      this.$nativeHandler('downloadFiels', params).then(res => {
        this.$toast.success('下载成功')
      }).catch(() => {
        this.$toast.fail('下载失败')
      })
    },
    // 因Android与ios下载统一废弃该方法
    async downLoad2(file) {
      let url = this.$formatURL(file.fileUrl, `${process.env.VUE_APP_ADS_STATIC}/`)
      const name = file.fileName || new Date().getTime()
      if (this.abelWaterTypes.includes(file.type)) {
        if (judgeSys() === 'ios') {
          url = `${this.waterMarkDownUrl}${file.id}`
        } else {
          await this.getBase64WaterMark(file.id).then(dataUrl => {
            url = dataUrl
            Cookies.set('waterMarkDownName', name)
          })
        }
      }
      // console.log('链接地址', url)

      if (judgeSys() === 'ios') {
        const params = { downloadURL: url, fileName: name }
        this.$nativeHandler('downloadFiels', params).then(res => {
          this.$toast.success('下载成功')
        }).catch(() => {
          this.$toast.fail('下载失败')
        })
        return
      }

      if (file.type === 'png' || file.type === 'jpg' || file.type === 'jpeg' || file.type === 'bmp') {
        // 图片则转换为base64保存
        /* let base64 = ''
        const img = new Image()
        img.crossOrigin = ''
        img.src = url
        img.onload = () => {
          base64 = this.image2Base64(img)
          const base64ImageData = base64.replace('data:image/png;base64,', '')
          console.log('base64ImageData', base64ImageData)
          this.$nativeHandler('base64ImageToAlbum', { base64ImageData }).then(res => {
            // this.$toast.success('下载成功')
          }).catch(() => {
            // this.$toast.fail('下载失败')
          })
        } */

        /* // 当前url为base64编码时
        const base64ImageData = url.replace('data:application/octet-stream;base64,', '')
        this.$nativeHandler('base64ImageToAlbum', { base64ImageData }).then(res => {
          // this.$toast.success('下载成功')
        }).catch(() => {
          // this.$toast.fail('下载失败')
        })

        return */
      }

      /*
      //TODO: PDF转换为base64无法实现跨域转换
      if (file.type === 'pdf') {
        // PDF文件则转换为base64保存
        this.getBase64(url).then(base64 => {
          const pdfBase64Data = base64.replace('data:application/pdf;base64,', '')
          this.$nativeHandler('savePdf2Album', { pdfBase64Data }).then(res => {
            this.$toast.success('下载成功')
          }).catch(() => {
            this.$toast.fail('下载失败')
          })
        })
        return
      } */

      const eleLink = document.createElement('a')
      eleLink.download = name
      eleLink.style.display = 'none'
      // eleLink.target = '_blank'
      // 字符内容转变成blob地址
      // let blob = new Blob([url]);
      // eleLink.href = URL.createObjectURL(blob);
      eleLink.href = url
      // 触发点击
      document.body.appendChild(eleLink)
      eleLink.click()
      // console.log(eleLink)
      // 然后移除
      document.body.removeChild(eleLink)

      /*
      TODO:跨域下载后无法打开
      const issafariBrowser = /Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)
      // 是否使用Safari浏览器下载
      if (issafariBrowser) {
        var link = document.createElement('a')
        link.target = '_blank'
        link.href = url
        if (link.download !== undefined) {
          link.download = name
        }
        if (document.createEvent) {
          var e = document.createEvent('MouseEvents')
          e.initEvent('click', true, true)
          link.dispatchEvent(e)
          return true
        }
      } else {
        const blob = new Blob([url])
        saveAs(blob, name)
        // saveAs(url, filename)
      } */
    },
    // 富文本图片查看
    handleViewImage(e) {
      // console.log(e,e.target.currentSrc)
      if (e.target.nodeName === 'IMG') {
        ImagePreview({
          images: [e.target.currentSrc], // e.target.currentSrc 为当前图片src
          showIndex: false,
          loop: false
        })
      }
    },
    // 获取水印文件
    getBase64WaterMark(id) {
      return new Promise((resolve, reject) => {
        getWatermarkFile(id).then(res => {
          const file = res.data
          // console.log(file)
          const reader = new FileReader()
          reader.readAsDataURL(file)
          reader.onload = (e) => {
            const dataUrl = e.target.result
            resolve(dataUrl)
          }
        }).catch(() => {
          reject('文件读取失败')
        })
      })
    },
    // 获取复制内容
    getCopyContent() {
      const el = this.$refs.htmlcontent
      if (el) {
        const content = el.innerText
        if (content && content.length > 0) {
          return content
        }
      }
      return ''
    },
    copyText() {
      /* const el = this.$refs.htmlcontent
      if (el) {
        const content = el.innerText
        if (content && content.length > 0) {
          navigator.clipboard.writeText(content)
            .then(() => {
              this.$toast.success('复制成功')
            })
            .catch(() => {
              this.$toast.error('复制失败')
            })
          return
        }
      } */
      const content = this.getCopyContent()

      if (content === '') {
        this.$toast('当前没有可复制的内容')
        return
      }
      this.clipboardCopyContent = content
      this.$nextTick(() => {
        const that = this
        const clipboard = new Clipboard('.btn-copy-content')
        clipboard.on('success', e => {
          // console.log('复制成功', e)
          that.$toast.success('复制成功')
          // 释放内存
          clipboard.destroy()
        })
        clipboard.on('error', e => {
        // 不支持复制
          // console.log('该浏览器不支持自动复制')
          that.$toast.error('暂不支持自动复制')
          // 释放内存
          clipboard.destroy()
        })
      })
    }
  }
}

</script>

<style lang="less" scoped>
.help-center-list-page{
  min-height: 100vh;
  width: 100vw;
  background-color: #fff;
  padding-top: 44PX;
  box-sizing: border-box;
  /deep/ .van-overlay{
    z-index: 900 !important;
  }
  /deep/ .van-popup--left{
    z-index: 901 !important;
  }
}
.help-list-header{
  position: fixed;
  width: 100%;
  z-index: 99;
  padding:10px;
  height: 44px;
  box-sizing: border-box;
  background: #FFFFFF;
  box-shadow: 0px 2px 6px 0px rgba(115, 115, 115, 0.08);
  display: flex;
  align-items: center;
  align-content: space-between;
  .icon-menu{
    width: 22px;
    height: 22px;
    background: #333333;
    background:url(~@/assets/icon-menu.png) no-repeat;
    background-size: 22px 22px;
  }
  .search-cell{
    flex: 1;
    margin-right: 26px;
    height: 26px;
    background: #F5F6F7;
    border-radius: 13px;
    /deep/ .search-input{
      background:#F5F6F7;
      .search-value{
        background:#F5F6F7;
      }
    }
  }
}
.help-center-list-main{
  background: #fff;
}
.help-list-header ~.help-center-list-main{
  padding-top: 44px;
}
.detail-main-page{
  padding: 0 10px 20px;
  .detail-title{
    padding: 15px 0;
    line-height: 1.2;
    color: #333333;
    letter-spacing: 1px;
    font-size: 16px;
    font-weight: bold;
    h1{
      font-size: 16px;
    }
    .d-time{
      color: #AAAAAA;
      line-height: 16px;
      font-size: 12px;
      letter-spacing: 1px;
      font-weight: normal;
      margin-top: 10px;
      display: flex;
      align-items: center;
      .icon-view{
        margin-left: 10px;
        display: flex;
        align-items: center;
        &::before{
          content: '';
          width: 16px;
          height: 16px;
          margin-right: 5px;
          background: url(~@/assets/icon-view.png) no-repeat;
          background-size: 16px 16px;

        }
      }
    }
  }
  .detail-content{
    width: 100%;
    margin-bottom: 20px;
    overflow: auto;
    line-height: 1.8;
    font-size: 14px !important;
    /deep/ img{
      max-width: 100% !important;
      height: auto !important;
    }
  }

  .attach-box{
    h1{
      height: 22px;
      margin-bottom: 10px;
      font-size: 16px;
      color: #333333;
      line-height: 22px;
      letter-spacing: 1px;
    }
    .attach-list{
      .list{
        display: flex;
        align-items: center;
        margin-bottom:10px;
        a{
          color: #333;
        }
        .att-icon{
          width: 16px;
          height: 16px;
          margin-right: 10px;
          background-size: 16px 16px;
          background-repeat: no-repeat;
          background-image: url(~@/assets/fileType/file.png);
          // excel、word、ppt、pdf、图片、ZIP
          &.xlsx{
            background-image: url(~@/assets/fileType/excel.png);
          }
          &.word{
            background-image: url(~@/assets/fileType/word.png);
          }
          &.ppt{
            background-image: url(~@/assets/fileType/ppt.png);
          }
          &.pdf{
            background-image: url(~@/assets/fileType/pdf.png);
          }
          &.img{
            background-image: url(~@/assets/fileType/img.png);
          }
          &.zip{
            background-image: url(~@/assets/fileType/zip.png);
          }
        }
        .att-name{
          // flex:1;
          max-width: 300px;
          line-height: 1.2;
          font-size: 12px;
          overflow: hidden;
        }
        .btn-down{
          margin-left: 20px;
          font-size: 12px;
          color: #40AEFF;
          width:66px;
          line-height:22px;
          border-radius:2px;
          text-align: center;
          text-decoration: none;
        }
      }
    }
  }
  .article-opt{
    margin-top: 28px;
    padding: 28px 30px 20px;
    border-top: #EFEFEF 1px solid;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .txt{
      position: absolute;
      left: 50%;
      top: -8px;
      z-index: 9;
      transform: translateX(-50%);
      height: 16px;
      line-height: 16px;
      font-size: 12px;
      background: #fff;
      color: #999999;
      letter-spacing: 1px;
    }

    .btn-zan{
      min-width: 102px;
      padding: 0 20px;
      box-sizing: border-box;
      cursor: pointer;
      height: 30px;
      border-radius: 15px;
      border: 1px solid #EAEAEA;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #999999;
      .svg-icon{
        font-size:20px;
        margin-right:5px;
      }
      .icon-cai{
        transform: rotateX(180deg);   /* 垂直镜像翻转 */
      }
      &.activve{
        .svg-icon{
          color:#3DC094;
        }
      }
    }
  }
  .article-page{
    margin-bottom: 15px;
    color: #999999;
    font-size: 12px;
    line-height: 16px;
    letter-spacing: 1px;
    &:last-child{
      margin-bottom: 0;
    }
    &.active{
      color: #333;
    }
  }
}
.video-content{
  margin: 10px auto 0;
  display: flex;
  justify-content: center;
  height: calc(60vh);
  video{
    max-width: 100%;
    height:auto;
    // height: 500px;
    object-fit: contain;
  }
}
.btn-copy{
  margin-top:20px;
  text-align: right;
  .btn{
    background: #00c8b4;
  }
}
</style>
